/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.config;

import nfse.gui.client.BrowseOptionsDialogBox;
import nfse.gui.client.DeleteDialogBox;
import nfse.gui.client.NetFSEClient;
import nfse.gui.client.NoteDialogBox;
import nfse.gui.client.OpenQueryDialogBox;
import nfse.gui.client.SetPasswordDialogBox;
import nfse.gui.query.QueryOptions;
import nfse.gui.query.TypeInfo;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.*;
import com.google.gwt.user.client.ui.*;
import com.gwtext.client.widgets.MessageBox;

public class ConfigurationTab extends FlexTable {
    final ListBox configs = new ListBox();

    HTML recordCountsHTML = new HTML();

    // FlexTable recordCountsTable = new FlexTable();

    FlexTable recordCountsSummaryTable = new FlexTable();

    // final FlexTable configurationTable = new FlexTable();

    final FlexTable criticalServersActionTable = new FlexTable();

    final FlexTable criticalServersTable = new FlexTable();

    final FlexTable recordCountsDataTable = new FlexTable();

    final FlexTable recordCountsTable = new FlexTable();

    final RadioButton dailyRadioButton = new RadioButton("emailradiobuttons");

    final TextBox emailAddressTextBox = new TextBox();

    final FlexTable emailReportsActionTable = new FlexTable();

    final FlexTable emailReportsTable = new FlexTable();

    final RadioButton neverRadioButton = new RadioButton("emailradiobuttons");

    private CriticalServerEntry selectedCriticalServer = null;

    private UserInfo selectedUser = null;

    public final SensorConfigTable sensorConfigsTable = new SensorConfigTable();

    final TextBox smtpPortTextBox = new TextBox();

    final TextBox smtpServerTextBox = new TextBox();

    final FlexTable usersActionTable = new FlexTable();

    final FlexTable usersTable = new FlexTable();

    final RadioButton weeklyRadioButton = new RadioButton("emailradiobuttons");

    private NetFSEClient parent = null;

    public ConfigurationTab(NetFSEClient parent) {
        this.parent = parent;

        checkIfAdmin();
        checkRecordCounts();
        recordCounts();
    }

    public synchronized void addCriticalServer(CriticalServerEntry cse) {

        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                criticalServers();
                NetFSEClient
                        .showGenericDialog("Add Critical Server",
                                "Critical server change succeeded. Changes will take effect in AutoSearch and the Dashboard the next time they run.");
            }
        };

        nfseService.addCriticalServer(cse, callback);

    }

    private void updateRecordCounts(DailyRecordCountInfo info) {

        if (info.dailyRecordCounts.length == 0) {
            while (recordCountsDataTable.getRowCount() > 0) {
                recordCountsDataTable.removeRow(0);
            }
            recordCountsDataTable.setHTML(0, 0, "No records have been processed in the last seven days.");
            return;
        }

        int numRows = info.dailyRecordCounts.length + 1;
        while (recordCountsDataTable.getRowCount() > numRows) {
            recordCountsDataTable.removeRow(numRows);
        }

        long totalRecords = 0;
        long totalRecordsDropped = 0;
        int daysExceeded = 0;

        recordCountsDataTable.addStyleName("nfsetable");
        recordCountsDataTable.addStyleName("nfsetbody");
        recordCountsDataTable.setHTML(0, 0, "<b>Date</b>");
        recordCountsDataTable.setHTML(0, 1, "<b>Record Count</b>");
        recordCountsDataTable.setHTML(0, 2, "<b>Records Dropped</b>");
        recordCountsDataTable.setHTML(0, 3, "<b>First Drop</b>");
        recordCountsDataTable.getRowFormatter().setStyleName(0, "nfseth");

        for (int i = 0; i < info.dailyRecordCounts.length; i++) {
            totalRecords += info.dailyRecordCounts[i].recordCount;
            totalRecordsDropped += info.dailyRecordCounts[i].exceededCount;
            if (info.dailyRecordCounts[i].exceededCount > 0)
                daysExceeded++;

            if (i % 2 == 0) {
                recordCountsDataTable.getRowFormatter().addStyleName(i + 1, "nfsetr");
            } else {
                recordCountsDataTable.getRowFormatter().addStyleName(i + 1, "nfsetrodd");
            }

            recordCountsDataTable.setHTML(i + 1, 0, info.dailyRecordCounts[i].date);
            recordCountsDataTable.getCellFormatter().addStyleName(i + 1, 0, "nfsetd");
            recordCountsDataTable.setHTML(i + 1, 1, info.dailyRecordCounts[i].recordCount + "");
            recordCountsDataTable.getCellFormatter().addStyleName(i + 1, 1, "nfsetd");
            recordCountsDataTable.setHTML(i + 1, 2, info.dailyRecordCounts[i].exceededCount + "");
            recordCountsDataTable.getCellFormatter().addStyleName(i + 1, 2, "nfsetd");
            recordCountsDataTable.setHTML(i + 1, 3, info.dailyRecordCounts[i].exceededTS + "");
            recordCountsDataTable.getCellFormatter().addStyleName(i + 1, 3, "nfsetd");
        }

        recordCountsSummaryTable.setHTML(0, 0, "<b>Total Records:</b>");
        recordCountsSummaryTable.getCellFormatter().addStyleName(0, 0, "tdright");
        recordCountsSummaryTable.setHTML(0, 1, totalRecords + "");
        recordCountsSummaryTable.getCellFormatter().addStyleName(0, 1, "tdright");
        recordCountsSummaryTable.setHTML(1, 0, "<b>Total Records Dropped:</b>");
        recordCountsSummaryTable.getCellFormatter().addStyleName(1, 0, "tdright");
        recordCountsSummaryTable.setHTML(1, 1, totalRecordsDropped + "");
        recordCountsSummaryTable.getCellFormatter().addStyleName(1, 1, "tdright");
        recordCountsSummaryTable.setHTML(2, 0, "<b>Time Not Collecting:</b>");
        recordCountsSummaryTable.getCellFormatter().addStyleName(2, 0, "tdright");
        recordCountsSummaryTable.setHTML(2, 1, info.timeNotCollecting + "");
        recordCountsSummaryTable.getCellFormatter().addStyleName(2, 1, "tdright");

        if (totalRecordsDropped > 0) {
            recordCountsHTML.setHTML("You have exeeded your record limit " + daysExceeded + " out of the last 7 days. "
                    + "<br>Contact <i>support@packetanalytics.com</i> to upgrade your record limit.");
        } else {
            recordCountsHTML.setHTML("");
        }

    }

    private void recordCounts() {

        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                updateRecordCounts((DailyRecordCountInfo) result);
            }
        };

        nfseService.getDailyRecordCounts(7, callback);

    }

    private void checkIfAdmin() {
        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        final ConfigurationTab configs = this;

        // final QueryOptions qo = getQueryOptions();

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                UserInfo userInfo = (UserInfo) result;

                if (userInfo != null && userInfo.admin) {
                    initConfiguration();
                } else {
                    parent.removeConfigs();
                }
            }
        };

        nfseService.getUserInfo(callback);
    }

    private void checkRecordCounts() {

        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                DailyRecordCountInfo info = (DailyRecordCountInfo) result;
                if (info.recordsDropped > 0) {
                    String html = "Net/FSE has exceeded its threshold of " + info.recordThreshold + " events/day.<br>";
                    html += "Over the past " + info.numDays + " days, " + info.recordsDropped
                            + " events were dropped. ";
                    html += "Net/FSE did not collect events for " + info.timeNotCollecting + " over this time period. ";
                    html += "Contact your Net/FSE administrator or email <i>support@packetanalytics.com</i> for information on increasing your record threshold.";
                    NetFSEClient.showGenericDialog("Warning: Record Threshold Exceeded", html);
                }
            }
        };

        nfseService.getDailyRecordCounts(7, callback);

    }

    private synchronized void criticalServers() {

        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                FlexTable.FlexCellFormatter formatter = criticalServersTable.getFlexCellFormatter();
                criticalServersTable.setStyleName("nfsetable");
                criticalServersTable.addStyleName("nfsetbody");
                selectedCriticalServer = null;
                CriticalServerEntry[] entries = (CriticalServerEntry[]) result;
                if (entries != null && entries.length > 0) {
                    if (criticalServersTable.getRowCount() == 0) {
                        int idx = -1;
                        criticalServersTable.getRowFormatter().setStyleName(0, "nfseth");
                        criticalServersTable.setHTML(0, ++idx, "");
                        criticalServersTable.setHTML(0, ++idx, "<b>Server IP</b>");
                        criticalServersTable.setHTML(0, ++idx, "<b>Note</b>");
                        criticalServersTable.setHTML(0, ++idx, "<b>As Src</b>");
                        criticalServersTable.setHTML(0, ++idx, "<b>As Dst</b>");
                    }
                    while (criticalServersTable.getRowCount() > 1)
                        criticalServersTable.removeRow(1);

                    RadioButton[] buttons = new RadioButton[entries.length];

                    for (int i = 0; i < entries.length; i++) {
                        final CriticalServerEntry tempCSE = entries[i];
                        int idx = -1;
                        if (i % 2 == 0) {
                            criticalServersTable.getRowFormatter().setStyleName(i + 1, "nfsetr");
                        } else {
                            criticalServersTable.getRowFormatter().setStyleName(i + 1, "nfsetrodd");
                        }

                        buttons[i] = new RadioButton("criticalservers");
                        if (i == 0) {
                            buttons[i].setChecked(true);
                            selectedCriticalServer = tempCSE;
                        }
                        buttons[i].addClickListener(new ClickListener() {
                            public void onClick(Widget sender) {
                                selectedCriticalServer = tempCSE;
                            }
                        });

                        criticalServersTable.setWidget(i + 1, ++idx, buttons[i]);

                        criticalServersTable.setHTML(i + 1, ++idx, entries[i].ip);
                        formatter.addStyleName(i + 1, idx, "nfsetd");
                        if (entries[i].note.length() == 0)
                            criticalServersTable.setHTML(i + 1, ++idx, "None");
                        else
                            criticalServersTable.setHTML(i + 1, ++idx, entries[i].note);
                        formatter.addStyleName(i + 1, idx, "nfsetd");
                        if (entries[i].asSrc)
                            criticalServersTable.setHTML(i + 1, ++idx, "<img src=\"image/checkmark.gif\">");
                        else
                            criticalServersTable.setHTML(i + 1, ++idx, "");
                        formatter.addStyleName(i + 1, idx, "nfsetd");
                        if (entries[i].asDst)
                            criticalServersTable.setHTML(i + 1, ++idx, "<img src=\"image/checkmark.gif\">");
                        else
                            criticalServersTable.setHTML(i + 1, ++idx, "");
                        formatter.addStyleName(i + 1, idx, "nfsetd");
                    }
                } else {
                    while (criticalServersTable.getRowCount() > 0)
                        criticalServersTable.removeRow(0);

                    criticalServersTable.setHTML(0, 0,
                            "No critical servers have been configured. Click Add to configure a critical server.");
                }

            }
        };

        nfseService.getCriticalServers(callback);
    }

    private synchronized void deleteCriticalServer(String ip) {
        final String tempIP = ip;
        MessageBox.confirm("Confirm", "Are you sure you want to delete the critical server entry for " + ip + "?",
                new MessageBox.ConfirmCallback() {
                    public void execute(String btnID) {
                        if (btnID.equals("yes")) {
                            ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

                            ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
                            endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

                            AsyncCallback callback = new AsyncCallback() {
                                public void onFailure(Throwable caught) {
                                    NetFSEClient.redirectToHome();
                                }

                                public void onSuccess(Object result) {
                                    criticalServers();
                                    NetFSEClient
                                            .showGenericDialog("Critical Server Change",
                                                    "Critical server change succeeded. Changes will take effect in AutoSearch and the Dashboard the next time they run.");
                                }
                            };

                            nfseService.removeCriticalServer(tempIP, callback);
                        }
                    }
                });
    }

    public synchronized void editCriticalServer(String ip, CriticalServerEntry cse) {

        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                criticalServers();
                NetFSEClient
                        .showGenericDialog(
                                "Critical Server Change",
                                "Critical server change succeeded. Changes will take effect in AutoSearch and the Dashboard the next time they run. Click 'Close' to continue.");
            }
        };

        nfseService.updateCriticalServer(ip, cse, callback);

    }

    private void emailReports() {
        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                EmailReportConfigs configs = (EmailReportConfigs) result;
                emailAddressTextBox.setText(configs.address);
                smtpServerTextBox.setText(configs.server);
                smtpPortTextBox.setText(configs.port + "");
                if (configs.frequency == 1)
                    dailyRadioButton.setChecked(true);
                else if (configs.frequency == 7)
                    weeklyRadioButton.setChecked(true);
                else
                    neverRadioButton.setChecked(true);
            }
        };

        nfseService.getEmailReportConfigs(callback);
    }

    public void initConfiguration() {

        final ConfigurationTab configurationTable = this;

        Hyperlink criticalServersAddLink = new Hyperlink("Add", "AddCriticalServer");
        criticalServersAddLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                CriticalServerDialogBox csdb = new CriticalServerDialogBox(configurationTable);
                csdb.setTitle("Add Critical Server");
                csdb.set(new CriticalServerEntry());
                csdb.setNew(true);
                csdb.show();
            }
        });

        Hyperlink criticalServersEditLink = new Hyperlink("Edit", "EditCriticalServer");
        criticalServersEditLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                if (selectedCriticalServer != null) {
                    CriticalServerDialogBox csdb = new CriticalServerDialogBox(configurationTable);
                    csdb.setTitle("Edit Critical Server Entry for " + selectedCriticalServer.ip);
                    csdb.setNew(false);
                    csdb.set(selectedCriticalServer);
                    csdb.show();
                }
            }
        });

        Hyperlink criticalServersDeleteLink = new Hyperlink("Delete", "DeleteCriticalServer");
        criticalServersDeleteLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                if (selectedCriticalServer != null)
                    deleteCriticalServer(selectedCriticalServer.ip);
            }
        });

        criticalServersActionTable.setWidget(0, 0, new Label("Actions: "));
        criticalServersActionTable.setWidget(0, 1, criticalServersAddLink);
        criticalServersActionTable.setHTML(0, 2, "|");
        criticalServersActionTable.setWidget(0, 3, criticalServersEditLink);
        criticalServersActionTable.setHTML(0, 4, "|");
        criticalServersActionTable.setWidget(0, 5, criticalServersDeleteLink);

        Hyperlink usersAddLink = new Hyperlink("Add", "AddUser");
        usersAddLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                UserDialogBox userDialogBox = new UserDialogBox(configurationTable);
                userDialogBox.setTitle("Add User");
                userDialogBox.set(new UserInfo());
                userDialogBox.setNew(true);
                userDialogBox.show();
            }
        });

        Hyperlink usersEditLink = new Hyperlink("Edit", "EditUser");
        usersEditLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                if (selectedUser != null) {
                    UserDialogBox userDialogBox = new UserDialogBox(configurationTable);
                    userDialogBox.setTitle("Edit " + selectedUser.userName);
                    userDialogBox.setNew(false);
                    userDialogBox.set(selectedUser);
                    userDialogBox.show();
                }
            }
        });

        Hyperlink usersDeleteLink = new Hyperlink("Delete", "DeleteUser");
        usersDeleteLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                if (selectedUser != null) {
                    // deleteUser(selectedUser.userName);
                }
            }
        });

        usersActionTable.setWidget(0, 0, new Label("Actions: "));
        usersActionTable.setWidget(0, 1, usersAddLink);
        usersActionTable.setHTML(0, 2, "|");
        usersActionTable.setWidget(0, 3, usersEditLink);
        usersActionTable.setHTML(0, 4, "|");
        usersActionTable.setWidget(0, 5, usersDeleteLink);

        dailyRadioButton.setText("Daily");
        weeklyRadioButton.setText("Weekly");
        neverRadioButton.setText("Never");
        emailReportsTable.setHTML(0, 0, "<b>Email Address</b>");
        emailReportsTable.setWidget(1, 0, emailAddressTextBox);
        emailReportsTable.setHTML(2, 0, "<b>SMTP Server</b>");
        emailReportsTable.setWidget(3, 0, smtpServerTextBox);
        emailReportsTable.setHTML(4, 0, "<b>SMTP Port</b>");
        emailReportsTable.setWidget(5, 0, smtpPortTextBox);
        emailReportsTable.setHTML(0, 1, "<b>Frequency</b>");
        emailReportsTable.setWidget(1, 1, dailyRadioButton);
        emailReportsTable.setWidget(2, 1, weeklyRadioButton);
        emailReportsTable.setWidget(3, 1, neverRadioButton);

        Hyperlink updateEmailReportsLink = new Hyperlink("Update", "UpdateEmailConfigs");
        updateEmailReportsLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {

                String server = smtpServerTextBox.getText().trim();
                if (server.length() == 0) {
                    MessageBox
                            .alert("Please enter the IP address or host name of your SMTP server in the SMPT Server field.");
                    return;
                }

                if (!server.equals("localhost") && server.indexOf(".") == -1) {
                    MessageBox.alert("The SMTP Server value entered is not valid. Please try again.");
                    return;
                }
                int port = 25;
                try {
                    port = Integer.parseInt(smtpServerTextBox.getText().trim());
                } catch (Exception e) {
                    MessageBox.alert("Please enter a valid port number for the SMTP server in the SMPT Port field.");
                    return;
                }

                String email = emailAddressTextBox.getText().trim();
                if (email.length() == 0) {
                    MessageBox.alert("You must enter a value in the Email Address field.");
                    return;
                }

                int atIdx = email.indexOf("@");
                if (atIdx == -1) {
                    MessageBox.alert("The email address entered is not valid. Please try again.");
                    return;
                }

                int dotIdx = email.indexOf(".", atIdx);
                if (dotIdx == -1 && !email.endsWith("@localhost")) {
                    MessageBox.alert("The email address entered is not valid. Please try again.");
                    return;
                }

                int frequency = 0;
                if (dailyRadioButton.isChecked())
                    frequency = 1;
                else if (weeklyRadioButton.isChecked())
                    frequency = 7;
                else
                    frequency = 0;
                EmailReportConfigs configs = new EmailReportConfigs();
                configs.address = email;
                configs.server = server;
                configs.frequency = frequency;
                configs.port = port;
                updateEmailReports(configs);
            }
        });

        emailReportsActionTable.setWidget(0, 0, new Label("Actions: "));
        emailReportsActionTable.setWidget(0, 1, updateEmailReportsLink);

        recordCountsTable.setHTML(0, 0, "<b>Record Counts</b>");
        recordCountsTable.setWidget(1, 0, recordCountsDataTable);
        recordCountsTable.setWidget(2, 0, recordCountsSummaryTable);
        recordCountsTable.setWidget(3, 0, recordCountsHTML);
        recordCountsTable.setHTML(4, 0, "<hr>");

        int idx = -1;

        configs.setVisibleItemCount(1);
        configs.addItem("Record Counts", "recordcounts");
        configs.addItem("Sensor Configuration", "sensorconfigs");
        configs.addItem("User Administration", "useradmin");
        configs.addItem("Critical Servers", "criticalservers");
        // configs.addItem("Email Report Configuration", "emailconfigs");

        configs.addChangeListener(new ChangeListener() {
            public void onChange(Widget sender) {
                String value = configs.getValue(configs.getSelectedIndex());
                if (value.equals("criticalservers")) {
                    configurationTable.setHTML(2, 0, "<h2>Critical Servers</h2>");
                    configurationTable.setWidget(3, 0, criticalServersActionTable);
                    configurationTable.setWidget(4, 0, criticalServersTable);
                } else if (value.equals("recordcounts")) {
                    configurationTable.setHTML(2, 0, "<h2>Record Counts</h2>");
                    configurationTable.setWidget(3, 0, recordCountsTable);
                    configurationTable.setHTML(4, 0, "");
                } else if (value.equals("useradmin")) {
                    configurationTable.setHTML(2, 0, "<h2>Users</h2>");
                    configurationTable.setWidget(3, 0, usersActionTable);
                    configurationTable.setWidget(4, 0, usersTable);
                } else if (value.equals("emailconfigs")) {
                    configurationTable.setHTML(2, 0, "<h2>Email Reports</h2>");
                    configurationTable.setWidget(3, 0, emailReportsActionTable);
                    configurationTable.setWidget(4, 0, emailReportsTable);
                } else if (value.equals("sensorconfigs")) {
                    configurationTable.setHTML(2, 0, "<h2>Sensor Configuration</h2>");
                    configurationTable.setWidget(3, 0, sensorConfigsTable);
                    configurationTable.setHTML(4, 0, "");
                    sensorConfigsTable.refresh();
                }
            }
        });

        configs.setSelectedIndex(0);
        configurationTable.setHTML(2, 0, "<h2>Record Counts</h2>");
        configurationTable.setWidget(3, 0, recordCountsTable);
        configurationTable.setHTML(4, 0, "");

        FlexTable configSelect = new FlexTable();
        configSelect.setHTML(0, 0, "<b>Select configuration:</b>");
        configSelect.setWidget(0, 1, configs);

        configurationTable.setWidget(++idx, 0, configSelect);
        configurationTable.setHTML(++idx, 0, "<hr>");

        // configurationTable.setHTML(++idx, 0, "<h2>Critical Servers</h2>");
        // configurationTable.setWidget(++idx, 0, criticalServersActionTable);
        // configurationTable.setWidget(++idx, 0, criticalServersTable);
        // configurationTable.setHTML(++idx, 0, "<hr>");
        // configurationTable.setHTML(++idx, 0, "<h2>Users</h2>");
        // configurationTable.setWidget(++idx, 0, usersActionTable);
        // configurationTable.setWidget(++idx, 0, usersTable);
        // configurationTable.setHTML(++idx, 0, "<hr>");
        // configurationTable.setHTML(++idx, 0, "<h2>Email Reports</h2>");
        // configurationTable.setWidget(++idx, 0, emailReportsActionTable);
        // configurationTable.setWidget(++idx, 0, emailReportsTable);

        emailReports();
        users();
        criticalServers();

        // tabs.add(configurationTable, "Configuration");

    }

    public void setTypes(TypeInfo typeInfo) {
        sensorConfigsTable.setTypes(typeInfo);
    }

    private void updateEmailReports(EmailReportConfigs configs) {
        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {

            }
        };

        nfseService.updateEmailReportConfigs(configs, callback);
    }

    public synchronized void users() {

        ConfigServiceAsync nfseService = (ConfigServiceAsync) GWT.create(ConfigService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(NetFSEClient.CONFIG_URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirectToHome();
            }

            public void onSuccess(Object result) {
                FlexTable.FlexCellFormatter formatter = usersTable.getFlexCellFormatter();
                usersTable.setStyleName("nfsetable");
                usersTable.addStyleName("nfsetbody");
                selectedUser = null;
                UserInfo[] users = (UserInfo[]) result;
                if (users != null && users.length > 0) {
                    if (usersTable.getRowCount() == 0) {
                        int idx = -1;
                        usersTable.getRowFormatter().setStyleName(0, "nfseth");
                        usersTable.setHTML(0, ++idx, "");
                        usersTable.setHTML(0, ++idx, "<b>User Name</b>");
                        usersTable.setHTML(0, ++idx, "<b>Real Name</b>");
                        usersTable.setHTML(0, ++idx, "<b>Admin</b>");
                    }
                    while (usersTable.getRowCount() > 1)
                        usersTable.removeRow(1);

                    RadioButton[] buttons = new RadioButton[users.length];

                    for (int i = 0; i < users.length; i++) {
                        final UserInfo tempInfo = users[i];
                        int idx = -1;
                        if (i % 2 == 0) {
                            usersTable.getRowFormatter().setStyleName(i + 1, "nfsetr");
                        } else {
                            usersTable.getRowFormatter().setStyleName(i + 1, "nfsetrodd");
                        }

                        buttons[i] = new RadioButton("users");
                        if (i == 0) {
                            buttons[i].setChecked(true);
                            selectedUser = tempInfo;
                        }
                        buttons[i].addClickListener(new ClickListener() {
                            public void onClick(Widget sender) {
                                selectedUser = tempInfo;
                            }
                        });

                        usersTable.setWidget(i + 1, ++idx, buttons[i]);

                        usersTable.setHTML(i + 1, ++idx, users[i].userName);
                        formatter.addStyleName(i + 1, idx, "nfsetd");
                        usersTable.setHTML(i + 1, ++idx, users[i].realName);
                        formatter.addStyleName(i + 1, idx, "nfsetd");

                        if (users[i].admin)
                            usersTable.setHTML(i + 1, ++idx, "<img src=\"image/checkmark.gif\">");
                        else
                            usersTable.setHTML(i + 1, ++idx, "");
                        formatter.addStyleName(i + 1, idx, "nfsetd");
                    }
                } else {
                    while (usersTable.getRowCount() > 0)
                        usersTable.removeRow(0);

                    usersTable.setHTML(0, 0, "No users have been created. Click Add to create a user.");
                }

            }
        };

        nfseService.getUsers(callback);
    }

}
